package cn.wonderland.user.service.impl;

import cn.wonderland.basic.cons.PhoneRegistCon;
import cn.wonderland.basic.cons.WechatCons;
import cn.wonderland.basic.jwt.JwtUtils;
import cn.wonderland.basic.jwt.RsaUtils;
import cn.wonderland.basic.jwt.UserInfo;
import cn.wonderland.basic.util.AjaxResult;
import cn.wonderland.basic.util.BussinessException;
import cn.wonderland.basic.util.HttpUtil;
import cn.wonderland.basic.util.MD5Utils;
import cn.wonderland.org.domain.Employee;
import cn.wonderland.org.domain.Shop;
import cn.wonderland.org.mapper.EmployeeMapper;
import cn.wonderland.org.mapper.ShopMapper;
import cn.wonderland.system.domain.Menu;
import cn.wonderland.system.mapper.MenuMapper;
import cn.wonderland.system.mapper.PermissionMapper;
import cn.wonderland.user.domain.Logininfo;
import cn.wonderland.user.domain.User;
import cn.wonderland.user.domain.Wxuser;
import cn.wonderland.user.dto.AccountLoginDto;
import cn.wonderland.user.dto.WechatBinderDto;
import cn.wonderland.user.dto.WechatDto;
import cn.wonderland.user.mapper.LogininfoMapper;
import cn.wonderland.user.mapper.UserMapper;
import cn.wonderland.user.mapper.WxuserMapper;
import cn.wonderland.user.service.LoginService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Value("${jwt.rsa.pri}")
    private String priKey;

    /**
     * 账号密码登录
     *
     * @param dto
     */
    @Override
    public AjaxResult accountLogin(AccountLoginDto dto) {
        // 非空校验
        // 根据参数查询数据库中是否存在
        Logininfo logininfo = logininfoMapper.findByAccount(dto);
        if (logininfo == null) {
            throw new BussinessException("账号或密码错误！");
        }
        // 验证密码是否正确 salt+password
        String accountPwd = MD5Utils.encrypByMd5(logininfo.getSalt() + dto.getPassword());
        if (!accountPwd.equals(logininfo.getPassword())) {
            throw new BussinessException("账号或密码错误！");
        }
        Map<String, Object> result = getMap(logininfo);

        return AjaxResult.me().success(result);

    }

    /**
     * 微信登录
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WechatDto dto) {
        // 参数校验
        // 调用微信第二个接口，根据code获取token和openid
        String url = String.format(WechatCons.SECOND_INTER, WechatCons.APPID, WechatCons.SECRET, dto.getCode());
        String jsonStr = HttpUtil.httpGet(url);
        if (StringUtils.isBlank(jsonStr)) {
            throw new BussinessException("微信炸了！");
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(openid)) {
            throw new BussinessException("微信又炸了！");
        }
        // 根据openid查询wxuser是否有数据
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        if (wxuser != null) {
            // 有数据 返回登录成功
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            Map<String, Object> map = this.getMap(logininfo);
            return AjaxResult.me().success(map);
        }
        // 如果没有数据 返回resultObj = noBinder
        // 6.2.不存在告诉前端用户跳转到账号绑定页面，传递参数到前端，因为我们在下个接口需要使用
        StringBuffer sbr = new StringBuffer()
                .append("?accessToken=")
                .append(accessToken)
                .append("&openId=").append(openid);
        return AjaxResult.me().fail("nobinder").setResultObj(sbr);
    }

    @Override
    public AjaxResult wechatBinder(WechatBinderDto dto) {
        // 参数校验
        // 判断手机验证码是否正确
        String phoneCode = (String) redisTemplate.opsForValue().get(String.format(PhoneRegistCon.BINDER_REDIS_KEY, dto.getPhone()));
        if (StringUtils.isBlank(phoneCode) || !phoneCode.equals(dto.getVerifyCode())) {
            throw new BussinessException("验证码错误！");
        }
        // 根据token和openid调用第三个接口，获取用户信息
        String url = String.format(WechatCons.THIRD_INTER, dto.getAccessToken(), dto.getOpenId());
        String jsonStr = HttpUtil.httpGet(url);
        if (StringUtils.isBlank(jsonStr)) {
            throw new BussinessException("微信叒炸了！");
        }
        Wxuser wxuser = JSONObject.parseObject(jsonStr, Wxuser.class);
        if (wxuser == null) {
            throw new BussinessException("微信炸翻了！");
        }
        // 根据手机号查询user中是否有数据
        User user = userMapper.findByPhone(dto.getPhone());
        Logininfo logininfo = new Logininfo();
        if (user == null) {
            // 没有数据 添加三张表
            user = dto.getUser();
            // 1.添加logininfo
            BeanUtils.copyProperties(user, logininfo);
            logininfo.setDisable(true);
            logininfo.setType(1);
            logininfoMapper.add(logininfo);
            // 2.添加user
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        } else {
            logininfo = logininfoMapper.findByUserId(user.getId());
        }
        // 3.添加wxuser
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        // 登录成功，返回token和logininfo
        Map<String, Object> map = this.getMap(logininfo);
        return AjaxResult.me().success(map);
    }


    /**
     * 无状态token版本
     * @param logininfo
     * @return
     */
//    private Map<String, Object> getMap(Logininfo logininfo) {
//        // 后端生成UUID作为token  存到redis里
//        String token = UUID.randomUUID().toString();
//        //将用户数据和token存入到redis中
//        redisTemplate.opsForValue().set(token, logininfo, 2, TimeUnit.HOURS);
//        // 清空敏感信息
//        logininfo.setPhone(null);
//        logininfo.setPassword(null);
//        logininfo.setType(null);
//        // 保存token到redis
//        Map<String, Object> result = new HashMap<>();
//        result.put("token", token);
//        result.put("logininfo", logininfo);
//        return result;
//    }

    /**
     * jwt版本改造
     *
     * @param logininfo
     * @return
     */
    private Map<String, Object> getMap(Logininfo logininfo) {
        // 保存token到redis
        Map<String, Object> result = new HashMap<>();
        // 1 获取token 获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(priKey).getFile());
        UserInfo userInfo = new UserInfo();
        userInfo.setLogininfo(logininfo);

        if (logininfo.getType() == 0) { // 判断是否是后台人员，不然就不用查权限
            // 查询员工的按钮权限
            List<String> snList = permissionMapper.findByLogininId(logininfo.getId());
            // 查询员工的菜单权限
            List<Menu> menus =  menuMapper.findByLogininfoId(logininfo.getId());
            // 赋值
            userInfo.setSnList(snList);
            userInfo.setMenuList(menus);
            // 返回给前端
            result.put("permissions", snList);
            result.put("menus", menus);
            // 后台用户 有可能是店铺员工
            Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
            if (null != employee && null != employee.getShopId()) {
                Shop shop = shopMapper.findById(employee.getShopId());
                userInfo.setShop(shop);
            }
        }
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 3000);
        // 清空敏感信息
        logininfo.setPhone(null);
        logininfo.setPassword(null);
        logininfo.setType(null);
        result.put("token", token);
        result.put("logininfo", logininfo);
        return result;
    }
}
